package com.agree.common;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import cn.com.agree.afa.tci.ITradeInvoker;
import cn.com.agree.afa.tci.InvokerProvider;
import cn.com.agree.afa.util.future.IFuture;
@Component
public class AfaUtils {
	
	private static final Logger log = LoggerFactory
			.getLogger(AfaUtils.class);

	private static ITradeInvoker tradeInvoker = null;
	
	private static int count = 0;
	
	private static int second = 0;

	@Autowired
	private AfaConfiguration afaConfigurationAuto;
	
	private static AfaConfiguration afaConfiguration;
	
	/*public AfaUtils() {
		// 初始化RPC链接
		try {
			tradeInvoker = InvokerProvider.get(Configuration.getString("afa.url"));
		} catch (Exception e) {
			log.error("AFA初始化失败", e);
		}
	}*/
	
	@PostConstruct
	private void init() {
		afaConfiguration = this.afaConfigurationAuto;
		// 初始化RPC链接
		try {
			tradeInvoker = InvokerProvider.get(afaConfiguration.getUrl());
		} catch (Exception e) {
			log.error("AFA初始化失败", e);
		}
	}

	/**
	 * @category 访问AFA交易
	 * @param tranCode 交易码
	 * @param body 报文体
	 * @param appHead 报文应用头
	 */
	public static ReturnResult access(String tranCode, String body, String appHead, ReturnResult res) throws Exception {
		try {
			String msg = getMsg(tranCode, body, appHead);
			if (log.isInfoEnabled()) {
				log.info("AFA请求报文：\r\n" + msg.toString());
			}
			/*IFuture future = tradeInvoker.invoke(Configuration.getString("afa.module.name"), 
					Configuration.getString("afa.tran.name"), msg.toString());*/
			IFuture future = tradeInvoker.invoke(afaConfiguration.getModuleName(), 
					afaConfiguration.getTranName(), msg.toString());
			Object object = future.get();
			if (log.isInfoEnabled()) {
				log.info("AFA响应报文：\r\n" + String.valueOf(object));
			}
			Object msgObj = JSONObject.parseObject(String.valueOf(object)).get("SYS_HEAD");
			JSONObject sysHead = JSONObject.parseObject(String.valueOf(msgObj));
			//if(Configuration.getString("afa.msg.error.status").equals(sysHead.get("ReturnStatus"))) {
			if(afaConfiguration.getMsg().getErrorStatus().equals(sysHead.get("ReturnStatus"))) {
				res.setSuccess(false);
				res.setErrorLocation(2);
				res.setErrorMsg(sysHead.getString("ReturnMessage"));
				res.setErrorCode(sysHead.getString("ReturnCode"));
			} else {
				res.setResult(JSONObject.parseObject(String.valueOf(object)).get("RspInfo"));
			}
		} catch (Exception e) {
			throw e;
		}
		return res;
	}
	
	
	private static String getMsg(String tranCode, String body, String appHead) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String date = sdf.format(new Date());
		StringBuilder msg = new StringBuilder();
		//系统头
		msg.append("\"SYS_HEAD\":{")
				/*.append("\"ConsumerId\":\"").append(Configuration.getString(
						"afa.msg.ConsumerId")).append("\",")*/
				.append("\"ConsumerId\":\"").append(afaConfiguration.getMsg().getConsumerId()).append("\",")
				.append("\"TransServiceCode\":\"").append(tranCode).append("\",")
				.append("\"RequestDate\":\"").append(date.substring(0, 8)).append("\",")
				.append("\"RequestTime\":\"").append(date.substring(8)).append("\",")
				.append("\"ConsumerSeqNo\":\"").append(getConsumerSeqNo()).append("\",")
				/*.append("\"ConsumerIP\":\"").append(Configuration.getString(
						"afa.msg.ConsumerIP")).append("\",")
				.append("\"ServerIP\":\"").append(Configuration.getString(
						"afa.msg.ServerIP")).append("\",")
				.append("\"TranMode\":\"1\",")
				.append("\"MacValue\":\"").append(Configuration.getString(
						"afa.msg.ConsumerId")).append("\",")*/
				.append("\"ConsumerIP\":\"").append(afaConfiguration.getMsg().getConsumerIP()).append("\",")
				.append("\"ServerIP\":\"").append(afaConfiguration.getMsg().getServerIP()).append("\",")
				.append("\"TranMode\":\"1\",")
				.append("\"MacValue\":\"").append(afaConfiguration.getMsg().getConsumerId()).append("\",")
				.append("\"Reserve\":\"\"")
			.append("},");
		
		//应用头
		msg.append("\"APP_HEAD\":")
				.append(appHead == null || "".equals(appHead.trim()) ? "{}" : appHead)
			.append(",");
		
		//报文体
		if(body == null || "".equals(body.trim())) {
			body = "{}";
		}
		msg.append("\"ReqInfo\":").append(body);
		
		msg.insert(0, "{");
		msg.append("}");
		
		//设置报文固定长度
	/*	msg.insert(0, getFixLength(Configuration.getInt("afa.msg.fix.len"), 
				msg.toString().getBytes().length));*/
		
		return msg.toString();
	}

	/**
	 * 获取报文固定8位长度
	 * @param length
	 * @return
	 */
	private static String getFixLength(int fixLen, int valLen) {
		String lenStr = Integer.toString(valLen);
		StringBuilder res = new StringBuilder();
		for(int i = 0; i<fixLen - lenStr.length(); i++) {
			res.append("0");
		}
		res.append(lenStr);
		return res.toString();
	}
	
	/**
	 * 获取流水号
	 * @return
	 */
	private static synchronized String getConsumerSeqNo() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String date = sdf.format(cal.getTime());
		if(second != cal.get(Calendar.SECOND)) {
			second = cal.get(Calendar.SECOND);
			count = 0;
		}
		/*return Configuration.getInt("afa.msg.ConsumerSeqNo") 
				+ date + getFixLength(6, ++count);*/
		return afaConfiguration.getMsg().getConsumerSeqNo()
				+ date + getFixLength(6, ++count);
	}
}
